package com.example.smartpark.controller.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.smartpark.common.Result;
import com.example.smartpark.dto.ParkingLotAddDTO;
import com.example.smartpark.dto.ParkingLotUpdateDTO;
import com.example.smartpark.service.ParkingLotService;
import com.example.smartpark.vo.ParkingLotVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 停车场管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin/parking-lots")
public class ParkingLotController {

    @Autowired
    private ParkingLotService parkingLotService;

    /**
     * 分页获取停车场列表
     *
     * @param page 页码
     * @param size 每页数量
     * @param name 停车场名称（可选）
     * @param status 状态（可选）
     * @return 分页停车场列表
     */
    @GetMapping
    public Result<IPage<ParkingLotVO>> getParkingLotPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) Integer status) {
        log.info("分页获取停车场列表: page={}, size={}, name={}, status={}", page, size, name, status);
        
        IPage<ParkingLotVO> parkingLotPage = parkingLotService.getParkingLotPage(page, size, name, status);
        return Result.success(parkingLotPage);
    }

    /**
     * 获取停车场详情
     *
     * @param id 停车场ID
     * @return 停车场详情
     */
    @GetMapping("/{id}")
    public Result<ParkingLotVO> getParkingLotById(@PathVariable Integer id) {
        log.info("获取停车场详情: id={}", id);
        
        ParkingLotVO parkingLotVO = parkingLotService.getParkingLotById(id);
        return Result.success(parkingLotVO);
    }

    /**
     * 添加停车场
     *
     * @param parkingLotAddDTO 添加停车场DTO
     * @return 添加的停车场信息
     */
    @PostMapping
    public Result<ParkingLotVO> addParkingLot(@RequestBody @Valid ParkingLotAddDTO parkingLotAddDTO) {
        log.info("添加停车场: parkingLotAddDTO={}", parkingLotAddDTO);
        
        ParkingLotVO parkingLotVO = parkingLotService.addParkingLot(parkingLotAddDTO);
        return Result.success(parkingLotVO, "添加停车场成功");
    }

    /**
     * 更新停车场信息
     *
     * @param id 停车场ID
     * @param parkingLotUpdateDTO 更新停车场DTO
     * @return 更新后的停车场信息
     */
    @PutMapping("/{id}")
    public Result<ParkingLotVO> updateParkingLot(
            @PathVariable Integer id,
            @RequestBody @Valid ParkingLotUpdateDTO parkingLotUpdateDTO) {
        log.info("更新停车场: id={}, parkingLotUpdateDTO={}", id, parkingLotUpdateDTO);
        
        ParkingLotVO parkingLotVO = parkingLotService.updateParkingLot(id, parkingLotUpdateDTO);
        return Result.success(parkingLotVO, "更新停车场信息成功");
    }

    /**
     * 删除停车场
     *
     * @param id 停车场ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteParkingLot(@PathVariable Integer id) {
        log.info("删除停车场: id={}", id);
        
        boolean success = parkingLotService.deleteParkingLot(id);
        if (success) {
            return Result.success(null, "删除停车场成功");
        } else {
            return Result.error(500, "删除停车场失败");
        }
    }

    /**
     * 检查停车场名称是否已存在
     *
     * @param name 停车场名称
     * @param excludeId 排除的停车场ID（可选，用于更新时）
     * @return 是否存在
     */
    @GetMapping("/check-name")
    public Result<Boolean> checkNameExists(
            @RequestParam String name,
            @RequestParam(required = false) Integer excludeId) {
        log.info("检查停车场名称是否已存在: name={}, excludeId={}", name, excludeId);
        
        boolean exists = parkingLotService.checkNameExists(name, excludeId);
        return Result.success(exists);
    }

    /**
     * 获取停车场统计信息
     *
     * @param id 停车场ID
     * @return 停车场统计信息
     */
    @GetMapping("/{id}/stats")
    public Result<Map<String, Object>> getParkingLotStats(@PathVariable Integer id) {
        log.info("获取停车场统计信息: {}", id);
        
        // 获取停车场信息
        ParkingLotVO parkingLot = parkingLotService.getParkingLotById(id);
        if (parkingLot == null) {
            return Result.error(404, "停车场不存在");
        }
        
        // 计算统计信息
        Map<String, Object> stats = new HashMap<>();
        stats.put("total", parkingLot.getTotalSpaces());
        stats.put("available", parkingLot.getAvailableSpaces());
        stats.put("occupied", parkingLot.getTotalSpaces() - parkingLot.getAvailableSpaces());
        
        // 计算占用率
        double occupancyRate = 0;
        if (parkingLot.getTotalSpaces() > 0) {
            occupancyRate = (double)(parkingLot.getTotalSpaces() - parkingLot.getAvailableSpaces()) / parkingLot.getTotalSpaces() * 100;
        }
        stats.put("occupancy_rate", String.format("%.1f", occupancyRate));
        
        // 构造状态统计
        Map<String, Integer> statusCount = new HashMap<>();
        statusCount.put("available", parkingLot.getAvailableSpaces());
        statusCount.put("occupied", parkingLot.getTotalSpaces() - parkingLot.getAvailableSpaces());
        statusCount.put("maintenance", 0); // 可以通过查询获取维护中车位数量
        statusCount.put("reserved", 0);    // 可以通过查询获取预约车位数量
        stats.put("statusCount", statusCount);
        
        return Result.success(stats);
    }
} 